package com.rongshu.view.home.activity;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.rongshu.R;
import com.rongshu.utils.Common;
import com.rongshu.utils.Constant;
import com.rongshu.utils.KeyboardUtils;
import com.rongshu.utils.LoginUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.base.mvp.INetBean;
import com.rongshu.view.discovery.activity.UserHomePageActivity;
import com.rongshu.view.discovery.bean.AuthorDetailBean;
import com.rongshu.view.home.adapter.CommentAdapter;
import com.rongshu.view.home.contract.CommentDetailsView;
import com.rongshu.view.home.entity.CommentDetails;
import com.rongshu.view.home.entity.CommentReplysBean;
import com.rongshu.view.home.entity.ContentClass;
import com.rongshu.view.home.listener.OnItemFunctionClickListener;
import com.rongshu.view.home.presenter.CommentDetailsPresenter;
import com.rongshu.view.userInfo.activity.PersonDetailsActivity;
import com.rongshu.widget.XRelativeLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.utils.DensityUtil;
import com.utils.FastClickUtils;
import com.widget.titlebar.ImmersionBar;
import com.widget.titlebar.OnKeyboardListener;
import com.widget.toast.ToastUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.ResponseBody;

import static com.rongshu.utils.UserInfoUtils.getUserId;

public class CommentDetailsActivity extends BaseActivity<CommentDetailsPresenter> implements CommentDetailsView, OnItemFunctionClickListener {
    @BindView(R.id.relativie_layout_comment)
    XRelativeLayout relativie_layout_comment;
    @BindView(R.id.top_layout)
    RelativeLayout top_layout;
    @BindView(R.id.txt_top_title)
    TextView txt_top_title;
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.layout_empty)
    RelativeLayout layout_empty;
    @BindView(R.id.edt_chat_input)
    EditText edt_chat_input;
    //refresh,load
    private boolean isrefresh = true;
    //map
    private Map<String, Object> map = null;
    //msg
    private int user_id = 0;
    private int contribute_id = 0;
    private int Sort = 0;
    private int pageIndex = 1;
    private int pageSize = 10;
    private int reply_pageIndex = 1;
    private int reply_pageSize = 100;
    //manger
    private LinearLayoutManager manager = null;
    //adapter
    private CommentAdapter adapter = null;
    //request
    private static final int REQUEST_AT_USER = 0x01;
    //@的用戶信息
    private LinkedHashMap<String, AuthorDetailBean> authorDetailBeanMap = null;
    //local_position 局部刷新position
    private int local_position;
    //正则
    private String REGEX = "@[\\u4e00-\\u9fa5\\w….-]+ ";
    private Pattern pattern = null;
    private Matcher matcher = null;
    //评论ID,回复ID
    private int comment_id = 0, reply_id = 0;
    private int reply_user_id = -1;
    private String reply_content = null;
    //点赞position
    private int likePosition = 0;
    //intent
    private Intent intent = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImmersionBar bar = ImmersionBar.with(this);
        bar.reset().keyboardEnable(true).setOnKeyboardListener(new OnKeyboardListener() {
            @Override
            public void onKeyboardChange(boolean isPopup, int keyboardHeight) {

            }
        });
        if (ImmersionBar.isSupportStatusBarDarkFont()) {//是否支持修改状态栏字体颜色
            bar.transparentStatusBar()  //透明状态栏，不写默认透明色
                    .statusBarDarkFont(true)   //状态栏字体是深色，不写默认为亮色
                    .flymeOSStatusBarFontColor(R.color.color_2c2c2c)  //修改flyme OS状态栏字体颜色
                    .statusBarAlpha(0);
        } else {
            bar.transparentStatusBar()  //透明状态栏，不写默认透明色
                    .flymeOSStatusBarFontColor(R.color.black)  //修改flyme OS状态栏字体颜色
                    //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
                    .statusBarDarkFont(true, 1.0f);
        }
        bar.init();
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_comment_details_view;
    }

    @Override
    protected void initView() {
        //presenter
        setPresenter(new CommentDetailsPresenter(this), this);
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) top_layout.getLayoutParams();
        layoutParams.topMargin = DensityUtil.getStateBar(this);
        top_layout.setLayoutParams(layoutParams);
        intent = getIntent();
        if (intent != null) {
            contribute_id = intent.getIntExtra(Constant.INTENT_DATA, 0);
        }
        //title
        txt_top_title.setText("评论");
        //manager
        manager = new LinearLayoutManager(this);
        //@list
        authorDetailBeanMap = new LinkedHashMap<>();
        //adapter
        adapter = new CommentAdapter(this);
        adapter.setOnItemFunctionClickListener(this);
        adapter.setHasStableIds(true);
        //recyclerview
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter);
        //refresh
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                isrefresh = true;
                pageIndex = 1;
                refreshlayout.resetNoMoreData();
                getOneRecommendMsg();
            }
        });

        smartRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                isrefresh = false;
                pageIndex++;
                getOneRecommendMsg();
            }
        });
        smartRefreshLayout.autoRefresh();
    }

    @Override
    protected void initData() {
        edt_chat_input.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN) {
                    LinkedHashMap<Integer, Integer> atEndList = new LinkedHashMap<>();
                    String content = edt_chat_input.getText().toString();
                    //正则
                    pattern = Pattern.compile(REGEX);
                    matcher = pattern.matcher(content);
                    while (matcher.find()) {
                        atEndList.put(matcher.start(), matcher.end());
                        Log.i("size--string", content.substring(matcher.start(), matcher.end()));
                    }

                    //获取输入框光标位置
                    int position = edt_chat_input.getSelectionStart();
                    Log.i("size--position", position + "");
                    for (LinkedHashMap.Entry<Integer, Integer> entry : atEndList.entrySet()) {
                        if ((position < entry.getValue() && position > entry.getKey()) || position == entry.getValue()) {
                            //获取该位置的数据
                            String key = content.substring(entry.getKey(), entry.getValue());
                            content = content.replace(key, "");
                            //创建富文本
                            SpannableStringBuilder builder = new SpannableStringBuilder();
                            builder.append(content);
                            if (!TextUtils.isEmpty(content)) {
                                //正则
                                matcher = pattern.matcher(content);
                                while (matcher.find()) {
                                    builder.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color_3cc051)),
                                            matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                }
                            }
                            edt_chat_input.setText(builder);
                            edt_chat_input.setSelection(builder.length());

                            if (authorDetailBeanMap.containsKey(key)) {
                                authorDetailBeanMap.remove(key);
                                Log.i("size", authorDetailBeanMap.size() + "");
                            }
                            return true;
                        }
                    }
                    return false;
                }
                return false;
            }
        });

        //添加layout大小发生改变监听器
        relativie_layout_comment.setListener(new XRelativeLayout.InputWindowListener() {
            @Override
            public void show() {
                edt_chat_input.setPadding(40, 10, 10, 10);
            }

            @Override
            public void hidden() {
                edt_chat_input.setPadding(10, 10, 10, 10);
            }
        });
    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    /**
     * 获取文章详情下的评论
     */
    private void getOneRecommendMsg() {
        user_id = getUserId();
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("contribute_id", contribute_id);
        map.put("Sort", Sort);
        map.put("pageIndex", pageIndex);
        map.put("pageSize", pageSize);
        presenter.getCommentDetail(user_id, contribute_id,
                Sort, pageIndex, pageSize, Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 获取单个评论下的所有回复
     */
    private void getOnecommentDetail(int comment_id, int pageSize) {
        user_id = getUserId();
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("comment_id", comment_id);
        map.put("pageIndex", reply_pageIndex);
        map.put("pageSize", reply_pageSize);
        presenter.getOnecommentDetail(user_id, comment_id, reply_pageIndex, reply_pageSize,
                Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 文章评论/评论回复/回复回复
     */
    private void postCommentOrReplyAdd(int comment_id, int reply_id, String content) {
        //user_id
        user_id = getUserId();
        if (user_id == 0) {
            LoginUtils.toLogin(this);
            return;
        }
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("contribute_id", contribute_id);
        map.put("comment_id", comment_id);
        map.put("reply_id", reply_id);
        ContentClass contentClass = new ContentClass();
        contentClass.setContents(content);
        contentClass.setTitle(null);
        StringBuilder aiteStrsb = new StringBuilder();
//        if (reply_user_id != -1) {
//            aiteStrsb.append(reply_user_id);
//        }
        for (Map.Entry<String, AuthorDetailBean> entry : authorDetailBeanMap.entrySet()) {
            if (!TextUtils.isEmpty(aiteStrsb)) {
                aiteStrsb.append(",");
            }
            aiteStrsb.append(entry.getValue().getUser_id_to());
        }
        contentClass.setAiteStr(aiteStrsb.toString());
        contentClass.setPenpalwill_id(null);
        presenter.postCommentOrReplyAdd(user_id, contribute_id, comment_id, reply_id,
                Common.encryptionSign(map), contentClass);
    }

    /**
     * 评论点赞（任何评论）
     */
    private void getCommentlike(int comment_id) {
        //user_id
        user_id = getUserId();
        if (user_id == 0) {
            LoginUtils.toLogin(this);
            return;
        }
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("type", 1);//1文章，2帖子
        map.put("obj_id", 1);//文章ID或者帖子ID TODO
        map.put("comment_id", comment_id);
        presenter.getCommentlike(
                (int) map.get("user_id"),
                (int) map.get("type"),
                (int) map.get("obj_id"),
                (int) map.get("comment_id"),
                Common.encryptionSign(map));
        map.clear();
    }

    @OnClick({R.id.layout_back, R.id.iv_at, R.id.txt_send})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_back:
                KeyboardUtils.hideSoftInput(this, edt_chat_input);
                setResult(RESULT_OK);
                finish();
                break;
            case R.id.iv_at:
                if (FastClickUtils.isFastClick()) {
                    return;
                }
                Intent intent = new Intent(this, SearchAtUserActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivityForResult(intent, REQUEST_AT_USER);
                break;
            case R.id.txt_send:
                if (FastClickUtils.isFastClick()) {
                    return;
                }
                String content = edt_chat_input.getText().toString();
                if (TextUtils.isEmpty(content)) {
                    ToastUtils.show("不能发送空评论");
                    return;
                }
                if (this.reply_user_id != -1 && !TextUtils.isEmpty(this.reply_content)) {
                    content = this.reply_content + content;
                }
                try {
                    content = URLEncoder.encode(content, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                postCommentOrReplyAdd(comment_id, reply_id, content);
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_AT_USER:
                    ImmersionBar.with(this).keyboardEnable(true, WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE
                            | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE).init();
                    AuthorDetailBean authorDetailBean = (AuthorDetailBean) data.getSerializableExtra(Constant.INTENT_DATA);
                    String content = null;
                    //获取输入框内容
                    String inputString = edt_chat_input.getText().toString();
                    if (authorDetailBean != null) {
                        //返回内容
                        String bi_name = "@" + authorDetailBean.getBi_name() + " ";
                        if (authorDetailBeanMap.containsKey(bi_name)) {//@同一个人2次不进行处理
                            return;
                        }
                        //@集合
                        authorDetailBeanMap.put(bi_name, authorDetailBean);
                        content = TextUtils.isEmpty(inputString) ? bi_name : inputString + bi_name;
                        //创建富文本
                        SpannableStringBuilder builder = new SpannableStringBuilder();
                        builder.append(content);
                        //正则
                        Pattern pattern = Pattern.compile(REGEX);
                        Matcher matcher = pattern.matcher(content);
                        while (matcher.find()) {
                            builder.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color_3cc051)),
                                    matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        }
                        edt_chat_input.setText(builder);
                        edt_chat_input.setSelection(content.length());
                    } else {
                        if (!TextUtils.isEmpty(inputString)) {
                            edt_chat_input.setSelection(inputString.length());
                        }
                    }
                    break;
            }
        }
    }

    /**
     * 评论数据
     *
     * @param responseBeanList
     */
    @Override
    public void onCommentMsg(List<CommentDetails.ResponseBean> responseBeanList) {
        if (adapter != null) {
            if (isrefresh) {
                smartRefreshLayout.finishRefresh();
                if (responseBeanList == null || responseBeanList.isEmpty()) {
                    smartRefreshLayout.setVisibility(View.GONE);
                    layout_empty.setVisibility(View.VISIBLE);
                } else {
                    smartRefreshLayout.setVisibility(View.VISIBLE);
                    layout_empty.setVisibility(View.GONE);
                    adapter.setResponseBeanList(responseBeanList);
                    adapter.notifyDataSetChanged();
                }
            } else {
                if (responseBeanList == null || responseBeanList.isEmpty()) {
                    smartRefreshLayout.finishLoadmoreWithNoMoreData();
                } else {
                    smartRefreshLayout.finishLoadmore();
                    adapter.addResponseBeanList(responseBeanList);
                    adapter.notifyDataSetChanged();
                }
            }
        }
    }

    @Override
    public void onOnecommentDetail(List<CommentReplysBean> commentReplysBeans) {
        if (adapter != null) {
            adapter.getResponseBeanList().get(local_position).setComment_replys(commentReplysBeans);
            adapter.notifyItemRangeChanged(local_position, adapter.getItemCount() - local_position);
        }
    }

    /**
     * 评论成功返回
     *
     * @param body
     */
    @Override
    public void onPostCommentOrReplyAdd(ResponseBody body) {

    }

    /**
     * 点击评论返回
     *
     * @param iNetBean
     */
    @Override
    public void onCommentlike(INetBean iNetBean) {
        if (iNetBean.getErrCode() == 0) {
            if (iNetBean.getErrMsg().equals("评论点赞成功")) {
                if (adapter != null) {
                    List<CommentDetails.ResponseBean> responseBeanList = adapter.getResponseBeanList();
                    if (responseBeanList != null) {
                        int likeCount = responseBeanList.get(likePosition).getLikeCount();
                        responseBeanList.get(likePosition).setLikeCount(likeCount + 1);
                        responseBeanList.get(likePosition).setIslike(1);
                        adapter.notifyItemRangeChanged(likePosition, 1, adapter.GIVELIKE);
                    }
                }
            }
        } else {
            ToastUtils.show(iNetBean.getErrMsg());
        }
    }

    /**
     * 清空标识
     */
    private void cleanIdentifying() {
        comment_id = 0;
        reply_id = 0;
        reply_user_id = -1;
        reply_content = null;
        //清空数据
        authorDetailBeanMap.clear();
        map.clear();
    }

    /**
     * item click
     */
    @Override
    public void onItemClickListener(int position,String contents, String bi_name, int id, int from_uid) {
        if (adapter != null) {
            List<CommentDetails.ResponseBean> responseBeans = adapter.getResponseBeanList();
            if (responseBeans != null && !responseBeans.isEmpty()) {
                KeyboardUtils.showKeyboard(true, this);
                //锁定光标
                edt_chat_input.setFocusable(true);
                edt_chat_input.setFocusableInTouchMode(true);
                edt_chat_input.requestFocus();
                //设置输入框提示
                edt_chat_input.setHint("回复：" + bi_name);
                comment_id = id;
                reply_id = 0;
                //防止意外
                this.reply_content = null;
                this.reply_user_id = -1;
            }
        }
    }

    /**
     * child click
     *
     * @param comment_id
     * @param reply_id
     */
    @Override
    public void onItemChildClickListener(int position, int replyPosition, String contents, String bi_name, int comment_id, int reply_id, int reply_user_id) {
        KeyboardUtils.showKeyboard(true, this);
        //锁定光标
        edt_chat_input.setFocusable(true);
        edt_chat_input.setFocusableInTouchMode(true);
        edt_chat_input.requestFocus();
        //设置输入框提示
        edt_chat_input.setHint("回复：" + bi_name);
        this.comment_id = comment_id;
        this.reply_id = reply_id;
        this.reply_content = "回复" + bi_name + ":";
        this.reply_user_id = reply_user_id;
    }

    /**
     * 展开收缩点击
     */
    @Override
    public void onItemExpandClickListener(boolean isExpanded, int pageSize, int comment_id, int local_position) {
        if (isExpanded) {
            this.local_position = local_position;
            getOnecommentDetail(comment_id, pageSize);
        }
    }

    /**
     * 头像点击
     */
    @Override
    public void onItemHeaderClickListener(int userid,boolean is_allow_browse_homepage) {
        //user_id
        user_id = getUserId();
        if (user_id == userid) {
            intent = new Intent(this, PersonDetailsActivity.class);
        } else {
            if (!is_allow_browse_homepage) {
                toast("由于对方的设置，你暂时无法浏览他的主页");
                return;
            }
            intent = new Intent(this, UserHomePageActivity.class);
            intent.putExtra("UserId", userid);
        }
        startActivity(intent);
    }

    /**
     * 点赞点击
     */
    @Override
    public void onItemGiveLikeClickListener(int comment_id, int position) {
        this.likePosition = position;
        getCommentlike(comment_id);
    }

    @Override
    public void onBackPressed() {
        KeyboardUtils.hideSoftInput(this, edt_chat_input);
        setResult(RESULT_OK);
        finish();
        super.onBackPressed();
    }
}
